package io.netty.example.http.websocketx.client;

import com.alibaba.fastjson.JSON;
import io.netty.example.http.websocketx.common.entity.NettyMessage;
import io.netty.example.http.websocketx.common.util.ByteNumberConverter;
import io.netty.example.http.websocketx.common.util.ByteObjConvert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author fuguangli
 * @description 前沿类
 * @Create date:    2017/4/28
 */
public class SocketClient {
    static final Logger logger = LoggerFactory.getLogger(SocketClient.class);

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {


        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

//        for(int i=0;i<100000;i++){
        final Socket socket = new Socket("127.0.0.1", 9090);
        socket.setKeepAlive(true);
        OutputStream out = socket.getOutputStream();

//        }


//        ObjectOutputStream writer = new ObjectOutputStream(out);
        NettyMessage message = new NettyMessage();


//        writer.write("i'm socket client");
//        writer.flush();

        new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        InputStream in = socket.getInputStream();
                        if (in.available() > 0) {
                            byte[] head = new byte[4];
                            in.read(head);//读取包头
                            int bodyLen = ByteNumberConverter.byteArrayToInt(head);

                            byte[] body = new byte[bodyLen];
                            in.read(body);


                            String jsonStr = new String(body, "utf-8");
                            NettyMessage recvMsg = JSON.parseObject(jsonStr, NettyMessage.class);
                            logger.info(recvMsg.toString());

//                            NettyMessage message1 = (NettyMessage) ByteObjConvert.byteToObject(bytes);
//                            System.out.println(jsonStr);
                        }
                        Thread.sleep(100);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        while (true) {
//            String msg = console.readLine();
            String msg = "上图显示了中，然后传";
            message.setMessage(msg);
            out.write(ByteObjConvert.wrapMsg(JSON.toJSONString(message)));
            out.flush();

            Thread.sleep(100);


        }


    }
}
